package com.geeker.common.core.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.geeker.common.constant.Constants;
import com.geeker.common.constant.RedisKeyPrefixConst;
import com.geeker.common.core.redis.RedisCache;
import com.geeker.common.exception.BusinessException;
import com.geeker.common.util.WebTools;
import com.geeker.common.core.domain.AccessUser;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description: TODO
 * @date 2024/12/6 15:48
 */
@Component
public class TokenService {

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public AccessUser getAccessUser() {
        // 获取请求携带的令牌
        String token = getToken();
        if (StringUtils.isBlank(token))
            return null;
        JWT jwt = JWTUtil.parseToken(token);
        String userKey =  RedisKeyPrefixConst.LOGIN_TOKEN_KEY + jwt.getPayload(Constants.LOGIN_USER_KEY).toString();
        AccessUser user = redisCache.getCacheObject(userKey);
        if (user == null)
            throw new BusinessException("获取用户信息异常");
        return user;
    }

    /**
     * 获取请求token
     *
     * @return token
     */
    private String getToken() {
        HttpServletRequest request = WebTools.getRequest();
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }


    /**
     * 创建令牌
     *
     * @param accessUser 用户信息
     * @return 令牌
     */
    public String createToken(AccessUser accessUser) {
        String token = IdUtil.fastUUID();
        accessUser.setToken(token);
        setUserAgent(accessUser);
        refreshToken(accessUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        return createToken(claims);
    }

    //设置用户代理信息
    private void setUserAgent(AccessUser accessUser) {
        UserAgent userAgent = UserAgentUtil.parse(WebTools.getRequest().getHeader("User-Agent"));
        String ip = WebTools.getIpAddress();
        accessUser.setIpaddr(ip);
//        accessUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        accessUser.setBrowser(userAgent.getBrowser().getName());
        accessUser.setOs(userAgent.getOs().getName());
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param accessUser
     * @return 令牌
     */
    public void verifyToken(AccessUser accessUser) {
        long expireTime = accessUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(accessUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param accessUser 登录信息
     */
    public void refreshToken(AccessUser accessUser) {
        accessUser.setLoginTime(System.currentTimeMillis());
        accessUser.setExpireTime(accessUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将accessUser缓存
        String userKey = RedisKeyPrefixConst.LOGIN_TOKEN_KEY + accessUser.getToken();
        redisCache.setCacheObject(userKey, accessUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        return JWTUtil.createToken(claims, secret.getBytes());
    }
}
